﻿using System;
using System.Data;
using System.Linq;
using System.Net.Mail;
using System.Web.Helpers;

namespace ECatalog.Models.Mailer
{
    public class Mailer : IMailer
    {
        public bool Send(string @from, string to, string message)
        {
            using (var client = new SmtpClient())
            {
                try
                {
                    var mailMessage = new MailMessage(from, to) { Body = message, IsBodyHtml = true };
                    client.Send(mailMessage);
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }

            }
        }

        public void AddToMailNotify(string email, string size, int modelId, int shopId)
        {
            using (var db = new DbContainer())
            {
                try
                {
                    var mailNotify = new MailNotify
                    {
                        ModelId = modelId,                        
                        ShopId = shopId,
                        Size = size,
                        MailNotifyEmail = email,
                        NotifyDate = DateTime.Now
                    };
                    db.MailNotifies.Add(mailNotify);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    
                }
            }
        }

        public void Notify(ModelSize modelSize)
        {
            using (var db = new DbContainer())
            {
                var notify = db.MailNotifies.Where(m =>!m.Send && m.ModelId == modelSize.ModelId && m.Size == modelSize.Size.Value && m.ShopId == modelSize.ShopId);
                try
                {
                    foreach (var mailNotify in notify)
                    {
                        const string message = "Поступил размер одежды который Вас интересовал";
                        var email = mailNotify.MailNotifyEmail;
                        var from = modelSize.Shop.Name;
                        if (Send(from, email, message))
                        {
                            mailNotify.Send = true;
                            db.Entry(mailNotify).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }                    
                }
                catch (Exception)
                {

                }
            }
        }
    }
}